﻿using System;
using System.Runtime.InteropServices;
using OpenGL.Exceptions;

namespace OpenGL
{
    static public class MessagePump
    {
        static bool work = true, isWorking = false;

        static public void Run(IntPtr windowHandle, Action renderAction)
        {
            if (isWorking)
            {
                throw new MessagePumpException();
            }

            isWorking = true;
            work = true;

            Loop(windowHandle, renderAction);

            isWorking = false;
        }

        static private void Loop(IntPtr windowHandle, Action renderAction)
        {
            NativeMessage msg;

            while (work)
            {
                if (PeekMessage(out msg, windowHandle, 0, 0, MessageFlag.PM_REMOVE))
                {
                    TranslateMessage(ref msg);
                    DispatchMessage(ref msg);
                }
                else
                {
                    renderAction();
                }
            }
        }

        static public void Stop()
        {
            work = false;
        }

        [DllImport("user32.dll")]
        static private extern bool PeekMessage(out NativeMessage lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, MessageFlag wRemoveMsg);
        [DllImport("user32.dll")]
        static private extern bool TranslateMessage(ref NativeMessage lpMsg);
        [DllImport("user32.dll")]
        static private extern IntPtr DispatchMessage(ref NativeMessage lpmsg);
    }
}
